import React, { useRef, useState, useEffect } from 'react';
import { connect } from 'dva';
import { Row, Image, Card, Popover, Button, Modal, message } from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import styles from '@/components/common/PateoTable/TableList.less';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { getDicByKey, findDicByCodeSort } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { routerRedux } from 'react-router-dom';

const DEFAULT_QUERY = () => ({
		version: '',
    systemType: '',
})

const mapStateToProps = (state: any) => ({
  listData: state?.operationTools?.pageData,
  loading: state.loading.effects['operationTools/getFetchPage'],
  dicData: state?.menu?.dicData ?? {},
  userProfile: state?.menu?.userProfile ?? {},
});

const appVersionControl = (props) => {
  const { dispatch, dicData, listData, loading, userProfile, location: { pathname = '/' }, } = props;
  const searchRef = useRef(null)
  const [query, setQuery] = useState(DEFAULT_QUERY())
  const { confirm, info } = Modal
  const systemTypeOptions = findDicByCodeSort(dicData, 'appSystemType')
  const pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
    ...listData?.pagination ?? {},
  }

  const fetchParams = { type: 'operationTools/getFetchPage', url: '/mscontent/tools/appversion/page' }
  const refreshList = () => {
    dispatch({
      type: fetchParams.type,
      payload: {
        url: fetchParams.url,
        ...query,
        ...pagination
      }
    })  
  }

  useEffect(() => {
    refreshList()
  }, [])

  const searchItems = [
    {
      title: '版本号',
      type: 'input',
      key: 'version',
    },
    {
      title: '操作系统',
      type: 'select',
      key: 'platform',
      selectOptions: systemTypeOptions,
      keyValue: ['dictKey', 'dictValue'],
    }
  ];

  const columns = [
		{
      title: '操作系统',
      width: 80,
      dataIndex: 'platform',
      render: (text: any, record: any) => {
        return getDicByKey(dicData, 'appSystemType', text?.toString())
      }
    },
    {
      title: '版本号',
      width: 80,
      dataIndex: 'version',
    },
    {
      title: '版本描述',
      dataIndex: 'description',
      ellipsis: true,
    },
		{
      title: '发布时间',
      dataIndex: 'publishTime',
    },
		{
      title: '安装包二维码',
      width: 100,
      dataIndex: 'qrcodeImgUrl',
			align: 'center',
			render: (text: string) => {
    
				return (
          <Popover trigger="click" content={<Image width={160} height={160} src={text} preview={false}/>}>
					  <Image width={20} height={20} src={text} preview={false}/>
          </Popover>
        )		
			}
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
    },
    {
      title: '操作',
      width: 150,
      fixed: 'right',
      render: (text: any, record: any) => {
        const btns = [
          {
            title: '编辑',
            key: 'appVersionControlEdit',
            auth: 'appVersionControl_doEdit',
            onConfirm: () => {
              handleUpdateVersion(record)
            },
          },
          {
            title: '删除',
            key: 'appVersionControlDel',
						type: 'danger',
            auth: 'appVersionControl_doDel',
            message: '是否确认删除？',
            Popconfirm: true,
            onConfirm: () => {
              dispatch({
                type: 'operationTools/delObj',
                payload: {
                  url: `/mscontent/tools/appversion/delete/${record.sid}`
                },
                callback: () => {
                  message.success('删除成功')
                  refreshList()
                }
              })
            },
          },
        ];
        return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
      },
    },
  ]

  const tableProps = {
    columns: columns, //列表标题信息
    dataSource: listData.list, //要渲染的数据信息
    loading: loading,
    rowKey: (record) => record.id, //接收每一行信息参数,设置每一行的key
    pagination: {
      ...pagination,
      showSizeChanger: true, //每页显示多少条
      showQuickJumper: true, //输数字快捷跳转
      showTotal: () => {
        return <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>;
      }, //展示页码信息栏
    }
  };

  const handleUpdateVersion = (formData) => {
    dispatch(
      routerRedux.push({
        pathname: '/operationTools/appVersionControl/appVersionDetail',
        state: { isEdit: !!formData, formData },
      })
    );
  }

  return (
      <div>
        <Card className={styles.standardTable}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={fetchParams}
            saveFormValues={(val: any) => setQuery(val)}
            handleFormReset={() => setQuery(DEFAULT_QUERY())}
            extraArgs={{
              current: 1,
              pageSize: 10
            }}
            onRef={e => {
              searchRef.current = e.current;
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          <Button
            key="addAppVersion"
            icon={<PlusOutlined />}
            size="small"
            type="primary"
            style={{ marginBottom: '12px' }}
            onClick={() => handleUpdateVersion()}
          >添加新版本</Button>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={fetchParams}
            formValues={query}
          />
        </Card>
      </div>
    );  
}

export default connect(mapStateToProps)(appVersionControl);
